import java.util.ArrayList;
import java.util.Iterator;
import java.util.Random;


public class HeartModel implements HeartModelInterface, Runnable{
	ArrayList beatObservers = new ArrayList();
	ArrayList bpmObservers = new ArrayList();
	int heartRate = 120;
	int time = 1000;
	Thread thread;
	Random rand = new Random(System.currentTimeMillis());
	
	public HeartModel(){
		thread = new Thread(this);
		thread.start();
	}
	public void initialize(){
		//setUpMid();
		//buildTrackAndStart();
	}
	
	public void run(){
		int lastrate=-1;
		
		for(;;){
			int change = rand.nextInt(10);
			if( rand.nextInt(2) == 0 ){
				change = 0 - change;
			}
			
			int rate = 60000/(time+change);
			heartRate = change;
			notifyBPMObservers();
			if ( rate<120 && rate > 50 ){
				time += change;				
				notifyBPMObservers();
				if ( rate != lastrate ){
					lastrate = rate;
					heartRate = lastrate;
					notifyBeatObservers();
				}
			}
			try{
				Thread.sleep(time);
			}catch(Exception e){}
		}		
	}
	
	public void on(){
		//sequencer.start();
		//setBPM(90);
	}
	
	public void off(){
		//setBPM(0);
		//sequencer.stop();		
	}
	
//	public void setBPM(int bpm){
//		this.bpm = bpm;
//		sequencer.setTempoInBPM(getBPM());
//		notifyBPMObservers();		
//	}
	
	public int getHeartRate(){
		return heartRate;		
	}
	
	void notifyBPMObservers() {
		
		Iterator iter = bpmObservers.iterator(); 
		while ( iter.hasNext())
		{
			BPMObserver obj = (BPMObserver) iter.next();
			obj.updateBPM();
		}
	}
	
	void notifyBeatObservers() {
		Iterator iter = beatObservers.iterator(); 
		while ( iter.hasNext())
		{
			BeatObserver obj = (BeatObserver) iter.next();
			obj.updateBeat();
		}
		
	}
	
	public void registerObserver( BPMObserver aObject ){
		bpmObservers.add( aObject );
	}
	
	public void registerObserver( BeatObserver aObject ){
		beatObservers.add( aObject );
	}
}
